/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.gui.knowledgeBase;

import org.utc.ia04.antsontheweb.knowledgeBase.KnowledgeBaseAgent;
import org.utc.ia04.antsontheweb.utilities.Requete;
import org.utc.ia04.antsontheweb.utilities.RequeteException;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;

public class KnowledgeBaseLearningGuiAgentBhv extends CyclicBehaviour
{
	//serialVersionUID
	private static final long serialVersionUID = 3666415576314106440L;

	public void action()
	{
		ACLMessage message = myAgent.receive();
		if(message == null)
			block();
		else
		{
			try
			{
				Requete r = Requete.deserialize_withException(message.getContent(), myAgent, message);
				switch(r.getType())
				{
					case Requete.KB_ANSWER :
						String content = r.getContent();
						if(content.equals(KnowledgeBaseAgent.DONE)) ((KnowledgeBaseLearningGuiAgent)myAgent).notifyFrame(KnowledgeBaseLearningGuiAgent.LEARNING_COMPLETE);
						else ((KnowledgeBaseLearningGuiAgent)myAgent).notifyFrame(content);
						break;
					case Requete.KB_GUI_FORCE_LOAD_URL :
						((KnowledgeBaseLearningGuiAgent)myAgent).loadPage(r.getContent());
						break;
					case Requete.KB_ERROR :
						((KnowledgeBaseLearningGuiAgent)myAgent).notifyFrame(KnowledgeBaseLearningGuiAgent.ERROR_OCCURED);
						break;
					default :
						errorOccured(KnowledgeBaseAgent.UNFORMATTED, message);
				}
			}
			catch (RequeteException e) { errorOccured(KnowledgeBaseAgent.UNFORMATTED, message); }
		}
	}
	
	private void errorOccured(String log, ACLMessage message)
	{
		ACLMessage answer = message.createReply();
		answer.setPerformative(ACLMessage.FAILURE);

		Requete r = new Requete(Requete.KB_ERROR, log);
		answer.setContent(r.serialize());

		myAgent.send(answer);
	}
}
